/**
 * Created by seeker910 on 2017/5/5.
 * @description 批量数据编辑保存，不包含sechma属性
 */
Rsd.define('Rsd.zen.dialog.ListDialog', {
    extend: 'Rsd.container.Dialog',
    requires: ['Rsd.control.Grid'],
    xtype: 'list-dialog',
    width: '80%',
    height: '70%',
    layout: 'vbox',
    readonly: true,
    autoLoad: false,
    items: [
        {
            xtype: 'grid',
            flex: 1,
            width: '100%', 
            autoScrollIntoView: true,
            rowdblclick: 'grid_row_dblclick',
            footBar: null,
            label: { space: 0 },
            toolBar: {
                xtype: 'search-tool-bar',
                height: 60,
                width: '100%'
            }
        },
        {
            //底部按钮按钮（buttons）容器
            xtype: 'container',
            header: null,
            height: 60,
            margin: '0 2 0 10',
            layout: 'hbox',
            width: 300,
            "style": { "float": 'right' },
            items: []
        }

    ],
    /**
    * @description 点击显示数据
    */
    rowDblClick: 'showItem',
    //底部按钮
    buttons: [],
    /** 
     *  @description 列表字段
     */
    //gridColumns
    /**
         * @description 优先级排第一
         * @description 获取数据源的 服务名 优先使用serviceName ,获取到的Service 将作为dataStore的proxy属性值
         */
    serviceName: null,
    /**
     * @description 优先级排第二
     * @description Rsd.data.Store数据源，支持本地数据已本地缓存数据
     * @description 在serviceName有效时，该属性将自动创建为 new Rsd.data.Store({proxy:app.getService(serviceName),listName:listMember})
     */
    dataStore: null,
    /**
     * @description 在serviceName有效时，listMember将作为dataStore的listName属性值
     */
    listMember: null,
     
     /**
     * @description form 设置
     */
    //form: {},
    formSchema:null,
    /**
     * */
    constructor: function ListDialog(config) {
        config = config || {};
        this.apply(config);  
    },
    /**
     * 
     */
    onBeforeInit:function onBeforeInit()
    {
        if(this.menu)
        {
            this.readonly = this.menu.readonly == undefined ? this.readonly : this.menu.readonly;
            this.modelType = this.modelType || this.menu.modelType;
            this.serviceName =  this.serviceName || this.menu.serviceName; 
            this.listMember = this.listMember || this.menu.listMember || 'rows';
            this.where = Rsd.arrayConcat(this.where ||[], this.menu.where||[]);
            this.sort = Rsd.arrayConcat(this.sort ||[], this.menu.sort||[]);

            this.searchColumns = Rsd.arrayConcat(this.searchColumns ||[], this.menu.searchColumns||[]);
            this.newButtons = Rsd.arrayConcat(this.newButtons||[],this.menu.newButtons||[]); 

            this.titleField =  this.titleField || this.menu.titleField || '';
            this.titleMember = this.titleMember || this.menu.titleMember || '';

            if(this.menu.formTitle)
            {
                this.form.title = this.menu.formTitle;
            }
            if(this.menu.formModelType)
            {
                this.form.modelType = this.menu.formModelType;
            }
        }

        //4.* 版本下，监控；下一个版本取消
        if(Rsd["version"].startWith('4.'))
        {
            if(this.formViewType)
            {
                this.form.viewType = this.formViewType;
                console.error('formViewType属性已取消，请使用form:{viewType:"XXXX"}方式代替');
            }
            if(this.formModelType)
            {
                this.form.modelType = this.formModelType;
                console.error('formModelType属性已取消，请使用form:{modelType:"XXXX"}方式代替');
            }
            if(this.formTitle)
            {
                this.form.title = this.formTitle;
                console.error('formTitle属性已取消，请使用form:{title:"XXXX"}方式代替');
            }
            if(this.titleField)
            {
                this.form.titleField = this.titleField;
                console.error('titleField属性已取消，请使用form:{titleField:"XXXX"}方式代替');
            }
            if(this.formFieldWidth)
            {
                this.form.fieldWidth = this.formFieldWidth;
                console.error('formFieldWidth属性已取消，请使用form:{fieldWidth:"45%"}方式代替');
            } 
            if(this.formHeight)
            {
                this.form.height = this.formHeight;
                console.error('formHeight属性已取消，请使用form:{height:"XXXX"}方式代替');
            }
            if(this.formWidth)
            {
                this.form.width = this.formWidth;
                console.error('formWidth属性已取消，请使用form:{width:"XXXX"}方式代替');
            }
            if(this.formData)
            {
                this.form.data = this.formData;
                console.error('formData属性已取消，请使用form:{data:{}}方式代替');
            } 
            if(this.formPosition)
            {
                this.form.position = this.formPosition;
                console.error('formPosition属性已取消，请使用form:{position:"XXXX"}方式代替');
            }
            if(this.formButtons)
            {
                this.form.buttons = this.formButtons;
                console.error('formButtons属性已取消，请使用form:{buttons:[]}方式代替');
            }
        } 

         this.callParent();
    },
    /**
     * 
     */
    onAfterInit: function onAfterInit() {

        var me = this;
        var btns = this.buttons || [];
        for (var i in btns) {
            this.items[1].items.push(Rsd.apply({ xtype: 'button', height: 40 }, btns[i]));
            if (this.items[1].items[i].xtype == 'button') {
                this.items[1].items[i].fn = this.items[1].items[i].handler;
                this.items[1].items[i].handler = function (sender, e) {
                    this.funApplyByIOC(this.fn, [me.getListData(), { parent: me, button: this, event: e }]);
                }
            }
        }

        this.callParent();
    },
    /*
     args :api 接口需要的参数
     * */
    load: function load(args, callback) {

        var me = this;
        //debugger;
        //console.log(args); 
        var grid = me.items[0];
        if (!(grid instanceof Rsd.control.Grid)) {
            console.error("me.items[0] is not Rsd.control.Grid");
            return;
        } 
        if(Rsd.isArray(args))
        { 
            grid.loadData(args);
            return;
        }
         if(!me.dataStore)
         {
                var _serviceName = me.serviceName || me.menu.serviceName || (me.modelSchema && me.modelSchema.listService); 
                if(!Rsd.isEmpty(_serviceName))
                {  
                    var _service = Rsd.app.getService(_serviceName);
                    if(_service)
                    {
                        me.dataStore = Rsd.create('Rsd.data.Store',{proxy:_service,listName:me.listMember||me.menu.listMember||'rows'}); 
                    } 
                }
         }
        
        if(me.dataStore)
        {
            grid.dataSource = me.dataStore;
        }  
        if(!grid.dataSource)
        {
            grid.dataSource =[];
            console.error('ListDialog：加载数据为空时，请设置属性dataStore或serviceName');   
            return;
        }

        Rsd.showWaiting(me.id, grid);
        
        //从服务端加载
        setTimeout(function () {
  
             var opt = me.getPagingOpt();  
             _args = Rsd.apply(args||{}, {
                 modelType: me.modelType,
                 pageSize: opt.pageSize || 100,
                 pageIndex: opt.pageIndex || 0
             });
      
             _args.where =  Rsd.arrayConcat(_args.where,me.where, me.menu && me.menu.where,me.toolBar && me.toolBar.getWhere()),
             _args.sort = Rsd.arrayConcat(_args.sort, me.sort, me.menu && me.menu.sort); 

             grid.loadData(_args || {}, function (resp) {
 
                 if (resp && resp.success) {
                     var _data = resp.data || {};
                     if (Rsd.isArray(_data)) {
                         me.setPagingOpt({ pageSize: opt.pageSize, pageIndex: 0, pageCount: 1, totalCount: _data.length });
                     }
                     else {
                         me.setPagingOpt({ pageSize: _data.pagesize, pageIndex: _data.pageindex, pageCount: _data.pagecount, totalCount: _data.total });
                     }
                 }
 
                 var _f = Rsd.callFunction(me, callback || function (__data) {
 
                     if (__data===undefined || __data === null) {
                         Rsd.alert('数据加载失败', '未获取到数据（网络故障）。');
                         return false;
                     }
                     if (Rsd.isArray(__data)) {
                         return true;
                     }
                     if (__data.success) { }
                     else {
 
                         if (Rsd.isEmpty(__data.msg)) { 
                             console.error('未知错误(UI0009),请查看日志。',resp);
                         }
 
                         return true;
                     }
 
                     return true;
 
                 }, arguments);
 
                 Rsd.closeWaiting(me.id);
                 //console.log('BaseListPage.loadData return: ' + _f);
                 return _f;
             });

        }, 100); 
        //this.callParent();
    },
    /**
    * 
    */
    _btn_search: function _btn_search() {

        //友好做法时：在查询条件发发生改变时，设置分页 {pageIndex: 0}
        if (this.whereIsChange()) {
            this.setPagingOpt({ pageIndex: 0 });
        }

        this.load({});
    },

    /**
    * 
    * */
    whereIsChange: function whereIsChange() {

        var _where = this.toolBar&&this.toolBar.getWhere();
        if (Rsd.isEmpty(this.____lastWhere) && Rsd.isEmpty(_where)) {
            return false;
        }
        if (Rsd.isEmpty(this.____lastWhere) || !Rsd.isEmpty(_where)) {
            return true;
        }
        if (!Rsd.isEmpty(this.____lastWhere) || Rsd.isEmpty(_where)) {
            return true;
        }
        if (this.____lastWhere.length != _where.length) {
            return true;
        }
        for (var i in _where) {

        }
        return true;
    },

    /**
    * @description 获取分页信息,在查询时，自动加上分页信息
    * */
    getPagingOpt: function getPagingOpt() {

        if(!Rsd.control || !Rsd.control.PagingBar)
        {
            return {};
        }
        if (this.items[0].footBar && this.items[0].footBar instanceof Rsd.control.PagingBar) {
            return this.items[0].footBar.getPaging();
        }
        return {};
    },

    /**
      * @description 设置分页信息,一般在查询条件发发生改变时，需重新设置分页 {pageIndex: 0}
    * */
    setPagingOpt: function setPagingOpt(opt) {
        
        if(!Rsd.control || !Rsd.control.PagingBar)
        {
            return {};
        }
        if (this.items[0].footBar && this.items[0].footBar instanceof Rsd.control.PagingBar) {
            return this.items[0].footBar.setPaging(opt);
        }
    },

    /**
     * @param {*} row 
     * @param {*} evt 
     */
    grid_row_dblclick: function grid_row_dblclick(row, evt,data) {
        //data['readonly'] = this.readonly;
        this.funApplyByIOC(this.rowDblClick, [row, evt,data]);
    },

    /**
    * @description 向表格中追加一行数据
    * */
    addRow: function addRow(row, edit) {
        if (this.items[0] instanceof Rsd.control.Grid) {
            this.items[0].newRow(row || {}, edit);
        }
    },

    /** 
    * @description 刷新数据
    * */
    refresh: function refresh() {
        
        if (this.items[0] instanceof Rsd.control.Grid) {
            this.items[0].refresh();
        }

    },

    /**
     *  @description 展示row数据
    */
    showItem: function showItem(row,evt,data ) {
        var readonly = this.readonly;//= data['readonly']
        var _record = row;
        var _schema = this.formSchema||this.modelSchema;
        var _titleField = this.form.titleField || this.titleMember || (this.menu && this.menu.titleField) || (this.menu && this.menu.titleMember) || (_schema && _schema.titleField);
        var _formTitle = this.form.title || ((_titleField == null || _titleField.length == 0) ? "明细[titleField未设置]" : ("明细["+(_record ? (_record[_titleField] || '-') : '*')+"]"));
        var _title = Rsd.template(_formTitle,_record||{});
        
        //console.log(this.form.title,this.form.fieldWidth,_title,_record);
        var form = Rsd.create(this.form.viewType, {

            formFields: this.formFields || (this.modelSchema && this.modelSchema.fields) || [],
            buttons: this.form.buttons || ['save', 'cancel'],
            modelSchema: _schema,
            parent: this,
            saveHandler:this.form.saveHandler,
            readonly: readonly,
            title: _title,
            fieldWidth:this.form.fieldWidth||'45%',
            height: this.form.height || 500,
            width: this.form.width || 480,
            data: row
        });
       
        switch (this.form.position) {

            case "left":
                form.showDialogOnLeft();
                break;
            case "right":
                form.showDialogOnRight();
                break;
            default:
                form.showDialog();
                break;
        }

    },

    /**
     * @private
     * */
    buildGridColumns: function buildGridColumns() {
        
        var _cols = Rsd.arrayConcat(this.gridColumns||[], this.opColumns||[]); 
 
        //为列自动关联forma方法
        for(var i in _cols)
        {
                var c = _cols[i];
                if(!c || c.format)
                {
                    continue;
                }
                if(this['format'+c.name])
                {
                    c.format = 'format' + c.name; 
                }
        }

        var grid = this.items[0];
        if(grid instanceof Rsd.control.Grid)
        {
            grid.buildColumns(_cols);
            return;
        }
      
        if(grid instanceof Object)
        {
            grid.columns = _cols;
        }
        
    },

    /**
    * @description 获取表格的数据
     * */
    getListData: function getListData() {
        var grid = this.items[0];
        return grid.rows;
    }



}, function (type) {

    //formFields
    var _formFieldsGetter = function () {
        if (this.__formFields == undefined) {
            this.__formFields = [];
        }
        return this.__formFields;
    };

    var _formFieldsSetter = function (value) {
        this.__formFields = value;
    }

    this.defineProperty(type, "formFields", _formFieldsGetter, _formFieldsSetter, true);

    //gridColumns
    var _columnsGetter = function () {
        if (this.__gridColumns == undefined) {
            this.__gridColumns = [];
        }
        return this.__gridColumns;
    };

    var _columnsSetter = function (value) {
        this.__gridColumns = value;

        this.buildGridColumns();
    }

    this.defineProperty(type, "gridColumns", _columnsGetter, _columnsSetter, true);

    //opColumns
    var _opColumnsGetter = function () {

        return this.__opColumns || [];
    };

    var _opColumnsSetter = function (value) {
        this.__opColumns = value;
        this.buildGridColumns();
    }

    this.defineProperty(type, "opColumns", _opColumnsGetter, _opColumnsSetter, true);



    //newButtons
    var _newButtonsGetter = function () {

        var _def_arr = [{ xtype: 'button', text: '查 询', visible: true, margin: '2 5 2 10', width: 120, handler: '_btn_search' }];
         
        return this.__newButtons || _def_arr;
    };

    var _newButtonsSetter = function (value) {

        var _value = value || [];
        for (var i in _value) {
            _value[i] = Rsd.apply({margin: '2 5 2 10' }, _value[i]);
        }
        var _def_arr = [{ xtype: 'button', text: '查 询', visible: true, margin: '2 5 2 10', width: 120, handler: '_btn_search' }];
        
        this.__newButtons = Rsd.arrayConcat(_def_arr, _value);

        this.toolBar.newButtons = this.__newButtons;
    }

    this.defineProperty(type, "newButtons", _newButtonsGetter, _newButtonsSetter, true);

    //searchColumns
    var _searchColumnsGetter = function _searchColumnsGetter() {

        if(!this.__searchColumns)
        {
                this.__searchColumns = [];
        }
        return this.__searchColumns;
    }

    var _searchColumnsSetter = function _searchColumnsSetter(value) {

        this.__searchColumns = value||[];
        this.toolBar.searchColumns = this.__searchColumns;
    }

    this.defineProperty(type, "searchColumns", _searchColumnsGetter, _searchColumnsSetter, true);


    var _toolBarGetter = function () {
        return this.items[0].toolBar;
    };

    var _toolBarSetter = function (value) {
        this.items[0].toolBar = value;
    }

    this.defineProperty(type, "toolBar", _toolBarGetter, _toolBarSetter, true);

    //
    var _footBarGetter = function () {
        return this.items[0].footBar;
    };

    var _footBarSetter = function (value) {
        this.items[0].footBar = value;
    }

    this.defineProperty(type, "footBar", _footBarGetter, _footBarSetter, true);

    //
    var _formGetter = function _formGetter()
    {
        if(Rsd.isEmpty(this.__form))
        {
            this.__form = {
                viewType:'Rsd.zen.dialog.FormDialog',//明细窗体类型
                modelType:this.modelType,
                fields:null,
                fieldWidth:'45%',//form 字段默认宽度
                titleField:'',
                title:'',
                height:'auto',//form 窗体高度
                width:1000, //form 窗体宽度
                position:'center', //表单展示位置 center,left,right  
                buttons:['save','delete','cancel'],//form 表单底部buttons
                data:{}//新增时 form默认数据 
            };
        }

       return this.__form;
    };

    var _formSetter  =function _formSetter(value)
    {  
        if(Rsd.isString(value))
        {
            this.form.viewType = value;
            return;
        }
       
        if(Rsd.isObject(value))
        {
            Rsd.apply(this.form,value); 
            return;
        }
        
    }

    this.defineProperty(type,"form", _formGetter, _formSetter,true);
});